package com.itheoma.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtils {
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;

    static {
        try {

            Properties properties = new Properties();
            properties.load(JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));

            driverClass = properties.getProperty("driverClass");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");


            Class.forName(driverClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取链接
    public static Connection getConnection() throws Exception {
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }


    //释放资源
    //做非空判断 避免空指针异常
    //每一条sql语句都trycatch是如果异常  下个资源也能正常释放
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        try {
            if (resultSet!=null){
                resultSet.close();
            }
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }

        try {
            if (statement!=null){
                statement.close();
            }
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }

        try {
            if (connection!=null){
                connection.close();
            }
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
    }
}